package cn.atzxc.qy.controller;

import cn.atzxc.qy.domain.ResponseResult;
import cn.atzxc.qy.domain.Rider;
import cn.atzxc.qy.domain.User;
import cn.atzxc.qy.service.RiderService;
import cn.atzxc.qy.service.UserService;
import cn.atzxc.qy.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RiderService riderService;

    /**
     * 获取用户信息
     * @param token 使用token获取到指定用户的ID
     * @return
     */
    @PostMapping("/getUserInfo")
    public ResponseResult queryUser(@RequestHeader("token") String token) throws Exception {

        //通过token解析出指定的用户名ID
        Claims claims = JwtUtil.parseJWT(token);
        String subject = claims.getSubject();

        // 根据用户ID，因为之前设置过redis的key，所以可以直接通过用户主键ID，从redis中 获取用户信息
        User user = userService.redisGetUserInfo(subject);
        System.out.println("用户信息是："+user);
        //从用户表的骑手ID中 查询出骑手的信息
        Rider userAuthState = riderService.getUserAuthState(token);
        if(userAuthState != null){
            user.setAuthStatus(userAuthState.getAuthStatus());
        }else{
            user.setAuthStatus("未认证");
        }

        return new ResponseResult(200, "查询成功", user);
    }

    /**
     * 更新指定用户的所属学校
     * @param token 通过token获取到指定用户的ID
     * @return
     */
    @PostMapping("/updateCollege")
    public ResponseResult updateCollege(@RequestHeader("token") String token,
                                        @RequestBody String collegeName) throws Exception {
        User user = userService.updateCollegeById(token,collegeName);
        //更新redis
        userService.redisSetUserInfo(token, user);
        return new ResponseResult(200,"更改成功", user);
    }



    @PostMapping("/updateuser")
    public ResponseResult updateUser(@RequestHeader("token") String token,
                                        @RequestBody User user) throws Exception{
        System.out.println(user);
        if(user == null){
            return new ResponseResult(400, "传递信息有误");
        }
        int num = userService.updateUserInfo(user);
        userService.redisSetUserInfo(token, user);
        System.out.println("num : "+num);
        return new ResponseResult(200, "修改成功");
    }


}
